﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：WebApiModule.cs
// 功能描述：TongTongMall.WebApi
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using TongTongMall.Json;
using TongTongMall.Modules;
using TongTongMall.Redis.Cache;
using TongTongMall.WebApi.WebApi.Configuration;
using TongTongMall.WebApi.WebApi.Controllers;
using TongTongMall.WebApi.WebApi.Controllers.Filters;

namespace TongTongMall.WebApi.WebApi
{
    [DependsOn(typeof(KernelModule), typeof(RedisCacheModule))]
    public class WebApiModule : BaseModule
    {
        public override void PreInitialize()
        {
            IocManager.AddConventionalRegistrar(new ApiControllerConventionalRegistrar());
            //自定义api解析模块
            IocManager.Register<IWebApiModuleConfiguration, WebApiModuleConfiguration>();
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

            var httpConfiguration = IocManager.Resolve<IWebApiModuleConfiguration>().HttpConfiguration;
            //注册IOC工厂，服务等
            InitializeAspNetServices(httpConfiguration);
            //注册全局异常，自定义绑定参数等
            InitializeFilters(httpConfiguration);

            InitializeFormatters(httpConfiguration);

            InitializeExpcetion(httpConfiguration);
        }

        private void InitializeAspNetServices(HttpConfiguration httpConfiguration)
        {
            httpConfiguration.Services.Replace(typeof(IHttpControllerActivator), new ApiControllerActivator(IocManager));
        }

        private void InitializeFilters(HttpConfiguration httpConfiguration)
        {
            httpConfiguration.MessageHandlers.Add(IocManager.Resolve<ResultWrapperHandler>());
            httpConfiguration.Filters.Add(IocManager.Resolve<TongTongMallExceptionFilterAttribute>());
        }

        private void InitializeExpcetion(HttpConfiguration httpConfiguration)
        {
            httpConfiguration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        }

        private static void InitializeFormatters(HttpConfiguration httpConfiguration)
        {
            //Remove formatters except JsonFormatter.
            foreach (var currentFormatter in httpConfiguration.Formatters.ToList())
            {
                if (!(currentFormatter is JsonMediaTypeFormatter))
                {
                    httpConfiguration.Formatters.Remove(currentFormatter);
                }
            }
            //移除webapi内置序列化对象为json的方式，替换为Newtonsoft序列方式且首字母小写。
            httpConfiguration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            //todo：可以规定时间序列化的格式，序列化类型等
            httpConfiguration.Formatters.JsonFormatter.SerializerSettings.Converters.Insert(0, new DefaultDateTimeConverter());

        }
    }
}
